package tt.dz.vo.request;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import tt.dz.common.BusinessException;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.ExceptionErrorCode;

public abstract class BaseRpcRequestVo
  implements RpcRequestVo
{
  public boolean equals(Object obj)
  {
    return EqualsBuilder.reflectionEquals(this, obj, new String[0]);
  }
  
  public int hashCode()
  {
    return HashCodeBuilder.reflectionHashCode(this, new String[0]);
  }
  
  public String toString()
  {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
  }
  
  public void validateRpcRequire()
    throws BusinessException
  {
    RequireFieldHolder requireFieldHolder = new RequireFieldHolder();
    RequireFieldHolder.FieldRequireConfig[] fieldRequireConfigs = requireFieldHolder.requestRequireFields(this);
    if ((fieldRequireConfigs == null) || (fieldRequireConfigs.length == 0)) {
      return;
    }
    try
    {
      for (RequireFieldHolder.FieldRequireConfig config : fieldRequireConfigs) {
        config.validateReqiure(this);
      }
    }
    catch (IllegalAccessException e)
    {
      throw new BusinessException(DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc(), e.getLocalizedMessage());
    }
  }
  
  public static final <T extends BaseRpcRequestVo> T convertAndValidateVo(String requestStr, Class<T> clazz)
    throws BusinessException
  {
    BaseRpcRequestVo vo = (BaseRpcRequestVo)JSONObject.parseObject(requestStr, clazz);
    if (vo == null) {
      throw new BusinessException(DzErrorCode.CommonErrorCode.PARAM_FORMAT_ERROR.value(), DzErrorCode.CommonErrorCode.PARAM_FORMAT_ERROR.getDesc());
    }
    vo.validateRpcRequire();
    return (T) vo;
  }
}
